//
//  MMNetworkRequest.m
//  EraPig
//
//  Created by Mac_Mini on 2021/3/8.
//

#import "MMNetworkRequest.h"
#import <AFNetworking/AFNetworking.h>
#import "UserModel.h"
#import "NSDate+MMAdd.h"
@implementation MMNetworkRequest

+ (instancetype)sharedNetworkingManage{
    static MMNetworkRequest *_network = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _network = [[MMNetworkRequest alloc]init];
    });
    return _network;
}

/// GET数据请求
/// @param urlString URL
/// @param parameters 参数
/// @param success 成功回调
/// @param failure 失败回调
- (void)GET:(NSString *)urlString
 parameters:(NSDictionary *)parameters
    success:(void (^)(id _Nonnull))success
    failure:(void (^)(NSError * _Nonnull))failure{
    // 初始化管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 上传普通的格式
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    // 响应
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", nil];
    manager.requestSerializer.timeoutInterval = 10.0f;
    
    if ([UserModel isLogin]) {
        [manager.requestSerializer setValue:[NSString stringWithFormat:@"%@ %@",[UserModel unarchive].token_type, [UserModel unarchive].access_token] forHTTPHeaderField:@"Authorization"];
//        [manager.requestSerializer setValue:@"ios" forHTTPHeaderField:@"platform"];
    }
    
    [manager GET:urlString parameters:parameters headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingFragmentsAllowed error:nil];
        if (success) {
            success(dic);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            failure(error);
        }
    }];
}
/// POST数据请求
/// @param urlString URL
/// @param parameters 参数
/// @param success 成功回调
/// @param failure 失败回调
- (void)POST:(NSString *)urlString
  parameters:(NSDictionary *)parameters
     success:(void (^)(id _Nonnull))success
     failure:(void (^)(NSError * _Nonnull))failure{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    // 上传普通的格式
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", nil];
    
    manager.requestSerializer.timeoutInterval = 10.0f;
//    urlString  = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    if ([UserModel isLogin]) {
        [manager.requestSerializer setValue:[NSString stringWithFormat:@"%@ %@",[UserModel unarchive].token_type, [UserModel unarchive].access_token] forHTTPHeaderField:@"Authorization"];
        [manager.requestSerializer setValue:@"ios" forHTTPHeaderField:@"platform"];
    }
    
    [manager POST:urlString parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        if (success) {
            success(dic);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
}

/// PUT数据请求含
/// @param urlString URL
/// @param parameters 参数
/// @param success 成功回调
/// @param failure 失败回调
- (void)PUT:(NSString *)urlString
 parameters:(nullable NSDictionary *)parameters
    success:(void (^) (id responseObject))success
    failure:(void (^) (NSError *error))failure{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    // 上传普通的格式
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", nil];
    
    manager.requestSerializer.timeoutInterval = 10.0f;

    if ([UserModel isLogin]) {
        [manager.requestSerializer setValue:[NSString stringWithFormat:@"%@ %@",[UserModel unarchive].token_type, [UserModel unarchive].access_token] forHTTPHeaderField:@"Authorization"];
        [manager.requestSerializer setValue:@"ios" forHTTPHeaderField:@"platform"];
    }
    NSMutableDictionary *headerDic = [NSMutableDictionary dictionary];
    if ([parameters objectForKey:@"Authorization"]) {
        [headerDic setValue:parameters[@"Authorization"] forKey:@"Authorization"];
    }
    [manager PUT:urlString parameters:parameters headers:headerDic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        if (success) {
            success(dic);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
}

/// POST数据请求含Body
/// @param urlString URL
/// @param parameters 参数
/// @param body body
/// @param success 成功回调
/// @param failure 失败回调
- (void)POST:(NSString *)urlString
  parameters:(nullable NSDictionary *)parameters
        body:(nullable NSDictionary *)body
     success:(void (^) (id responseObject))success
     failure:(void (^) (NSError *error))failure{
    AFURLSessionManager *manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlString parameters:parameters error:nil];
    [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [req setHTTPBody:[[[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:body options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding] dataUsingEncoding:NSUTF8StringEncoding]];
    [req setValue:[NSString stringWithFormat:@"%@ %@",[UserModel unarchive].token_type, [UserModel unarchive].access_token] forHTTPHeaderField:@"Authorization"];
    [req setValue:@"ios" forHTTPHeaderField:@"platform"];
    
    [[manager dataTaskWithRequest:req uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
            
    } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
        
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (!error) {
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                if (success) {
                    success(responseObject);
                }
            }
        }else{
            if (failure) {
                failure(error);
            }
        }
    }] resume];
}

/// PUT数据请求含Body
/// @param urlString URL
/// @param parameters 参数
/// @param body body
/// @param success 成功回调
/// @param failure 失败回调
- (void)PUT:(NSString *)urlString
 parameters:(nullable NSDictionary *)parameters
       body:(nullable NSDictionary *)body
    success:(void (^) (id responseObject))success
    failure:(void (^) (NSError *error))failure{
    AFURLSessionManager *manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"PUT" URLString:urlString parameters:parameters error:nil];
    [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [req setHTTPBody:[[[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:body options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding] dataUsingEncoding:NSUTF8StringEncoding]];
    [req setValue:[NSString stringWithFormat:@"%@ %@",[UserModel unarchive].token_type, [UserModel unarchive].access_token] forHTTPHeaderField:@"Authorization"];
    [req setValue:@"ios" forHTTPHeaderField:@"platform"];
    
    [[manager dataTaskWithRequest:req uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
            
    } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
        
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (!error) {
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                if (success) {
                    success(responseObject);
                }
            }
        }else{
            if (failure) {
                failure(error);
            }
        }
    }] resume];
}

/// 上传文件（单个上传，文件data上传）
/// @param urlString URL
/// @param parameters 参数
/// @param fileData 文件data
/// @param fileName 文件名
/// @param name fileData对应的key
/// @param success 成功回调
/// @param failure 失败回调
- (void)UPLOAD:(NSString *)urlString
    parameters:(nullable NSDictionary *)parameters
      fileData:(NSData *)fileData
      fileName:(NSString *)fileName
          name:(NSString *)name
       success:(void (^) (id responseObject))success
       failure:(void (^) (NSError *error))failure{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    // 上传普通的格式
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];

    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", nil];
    
    [manager POST:urlString parameters:parameters headers:@{
        @"Authorization":[NSString stringWithFormat:@"%@ %@",[UserModel unarchive].token_type, [UserModel unarchive].access_token],
        @"platform":@"ios"
    } constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:fileData name:name fileName:fileName mimeType:@"image/png"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        if (success) {
            success(dic);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
}

/// 上传文件（多个上传，文件data上传）
/// @param urlString URL
/// @param parameters 参数
/// @param files 要上传的文件数组  @{@"data":NSURL/NSData, @"key":name, @"filename":filename}
/// @param success 成功回调
/// @param failure 失败回调
- (void)UPLOAD:(NSString *)urlString
    parameters:(nullable NSDictionary *)parameters
         files:(NSArray <NSDictionary *>*)files
       success:(void (^) (id responseObject))success
       failure:(void (^) (NSError *error))failure{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    // 上传普通的格式
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];

    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", nil];
    
    [manager POST:urlString parameters:parameters headers:@{
        @"Authorization":[NSString stringWithFormat:@"%@ %@",[UserModel unarchive].token_type, [UserModel unarchive].access_token],
        @"platform":@"ios"
    } constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (NSDictionary *dic in files) {
            if ([dic[@"data"] isKindOfClass:[NSURL class]]) {
                [formData appendPartWithFileURL:dic[@"data"] name:dic[@"key"] fileName:dic[@"filename"] mimeType:@"multipart/form-data" error:nil];
            }else if ([dic[@"data"] isKindOfClass:[NSData class]]){
                [formData appendPartWithFileData:dic[@"data"] name:dic[@"key"] fileName:dic[@"filename"] mimeType:@"multipart/form-data"];
            }
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        if (success) {
            success(dic);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
}

/// 下载文件、图片
/// @param urlString URL
/// @param progress 进度
/// @param success 成功
/// @param failure 失败
- (void)DOWNLOAD:(NSString *)urlString
        progress:(void (^) (double progress))progress
         success:(void (^) (id responseObject))success
         failure:(void (^) (NSError *error))failure{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *req = [NSURLRequest requestWithURL:url];
    
    [[manager downloadTaskWithRequest:req progress:^(NSProgress * _Nonnull downloadProgress) {
            NSLog(@"下载进度：%@",downloadProgress);
        if (progress) {
            dispatch_async(dispatch_get_main_queue(), ^{
                progress(downloadProgress.fractionCompleted);
            });
        }
        } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
            NSString *path =[[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
            NSURL *url = [[NSURL alloc] initFileURLWithPath:path];
            return url;
        } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (!error) {
                    NSData *data = [NSData dataWithContentsOfURL:filePath];
                    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
                    NSString *imageFilePath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@",[[NSDate date] toStringByFormatter:@"yyyyMMddHHmm"], [filePath.lastPathComponent substringFromIndex:[filePath.lastPathComponent rangeOfString:@"."].location]]];
                    
                    [data writeToFile:imageFilePath atomically:YES];
                    if (success) {
                        success(imageFilePath);
                    }
                }else{
                    if (failure) {
                        failure(error);
                    }
                }
            });
        }] resume];
}
@end
